const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, '用户姓名不能为空'],
    trim: true,
    maxlength: [50, '用户姓名不能超过50个字符']
  },
  phone: {
    type: String,
    required: [true, '手机号码不能为空'],
    trim: true,
    match: [/^1[3-9]\d{9}$/, '请输入有效的手机号码']
  },
  password: {
    type: String,
    required: [true, '密码不能为空'],
    minlength: [6, '密码至少需要6个字符']
  },
  role: {
    type: String,
    enum: {
      values: ['user', 'maintainer', 'admin'],
      message: '角色只能是 user、maintainer 或 admin'
    },
    default: 'user'
  },
  avatar: {
    type: String,
    default: ''
  },
  email: {
    type: String,
    trim: true,
    lowercase: true,
    match: [/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/, '请输入有效的邮箱地址']
  },
  address: {
    type: String,
    maxlength: [200, '地址不能超过200个字符']
  },
  // 维修人员专用字段
  specialties: [{
    type: String,
    enum: ['electrical', 'plumbing', 'hvac', 'carpentry', 'painting', 'other']
  }],
  experience: {
    type: Number,
    min: [0, '工作经验不能为负数']
  },
  rating: {
    type: Number,
    min: [0, '评分不能低于0'],
    max: [5, '评分不能高于5'],
    default: 0
  },
  completedOrders: {
    type: Number,
    default: 0,
    min: [0, '完成订单数不能为负数']
  },
  isActive: {
    type: Boolean,
    default: true
  },
  lastLoginAt: {
    type: Date
  }
}, {
  timestamps: true,
  versionKey: false
});

// 密码加密中间件
userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  
  try {
    const salt = await bcrypt.genSalt(12);
    this.password = await bcrypt.hash(this.password, salt);
    next();
  } catch (error) {
    next(error);
  }
});

// 密码验证方法
userSchema.methods.comparePassword = async function(candidatePassword) {
  return await bcrypt.compare(candidatePassword, this.password);
};

// 转换为JSON时移除敏感信息
userSchema.methods.toJSON = function() {
  const userObject = this.toObject();
  delete userObject.password;
  return userObject;
};

// 创建索引
userSchema.index({ phone: 1 }, { unique: true });
userSchema.index({ email: 1 }, { sparse: true });
userSchema.index({ role: 1 });
userSchema.index({ isActive: 1 });

module.exports = mongoose.model('User', userSchema);